import 'package:flutter/material.dart';
import '../component/config_bottom_sheet.dart';
import '../component/drawer_widget.dart';
import '../models/article.dart';
import '../component/article_widget.dart';

class ReaderPage extends StatefulWidget {
  const ReaderPage({Key? key}) : super(key: key);

  @override
  _ReaderPageState createState() => _ReaderPageState();
}

class _ReaderPageState extends State<ReaderPage> {
  bool _hasCurArticle = false;
  double _contentFontSize = 16;
  double _lineSpacingTimes = 1.5;

  final ScrollController _scrollController = ScrollController();
  final ArticleModel _articleModel = ArticleModel();

  late StateSetter _updateArticleConfig;
  late Future<Article> _futureArticle = _articleModel.getNewArticle();

  void _refreshArticle() {
    _scrollController.animateTo(0,
        duration:
        const Duration(milliseconds: 500),
        curve: Curves.decelerate);
    _futureArticle = _articleModel.getNewArticle();
    setState(() {});
  }

  void _readFavoriteArticle(int index) {
    var titleAuthor = _articleModel.favoriteArticlesList[index];
    _scrollController.animateTo(0,
        duration: const Duration(milliseconds: 500), curve: Curves.decelerate);

    setState(() {
      _futureArticle = _articleModel.getFavoriteArticle(titleAuthor);
    });
  }

  void _updateReaderConfig(double contentFontSize, double lineSpacingTimes){
    _updateArticleConfig((){
      _contentFontSize = contentFontSize;
      _lineSpacingTimes = lineSpacingTimes;
    });
  }

  @override
  void initState() {
    super.initState();
    _articleModel.getPrefs().then((value) {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) {
          return SafeArea(
            child: GestureDetector(
              child: Material(
                child: FutureBuilder<Article>(
                  future: _futureArticle,
                  builder: (context, snapshot) {
                    if (snapshot.hasError) {
                      _hasCurArticle = false;
                      return Center(
                        child: SizedBox(
                          width: 256,
                          height: 64,
                          child: TextButton(
                            child: const Text("获取文章错误, 点击重试"),
                            onPressed: _refreshArticle,
                          ),
                        ),
                      );
                    } else if (snapshot.hasData) {
                      _hasCurArticle = true;
                      return StatefulBuilder(
                        builder: (context, setArticleState) {
                          _updateArticleConfig = setArticleState;
                          return ArticleWidget(
                            article: snapshot.data!,
                            contentFontSize: _contentFontSize,
                            lineSpacingTimes: _lineSpacingTimes,
                            scrollController: _scrollController,
                          );
                        },
                      );
                    } else {
                      _hasCurArticle = false;
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                  },
                ),
              ),
              onTap: () {
                if (_hasCurArticle) {
                  showModalBottomSheet(
                    context: context,
                    builder: (context) {
                      return ConfigBottomSheet(
                        articleModel: _articleModel,
                        updateConfigCallback: _updateReaderConfig,
                        refreshArticleCallback: _refreshArticle,
                      );
                    },
                  );
                }
              },
              onHorizontalDragEnd: (detail) {
                if (detail.velocity.pixelsPerSecond.dx > 0) {
                  Scaffold.of(context).openDrawer();
                }
              },
            ),
          );
        },
      ),
      drawer: SafeArea(
        child: SizedBox(
            width: 196,
            child: DrawerWidget(
              articleModel: _articleModel,
              readFavoriteArticleCallback: _readFavoriteArticle,
            )),
      ),
    );
  }
}
